<?php
/**
 * Controller allowing roles modification.
 * 
 * @version $Id: RolesController.php,v 1.1 2011-06-17 04:43:21 herve Exp $
 * @copyright 2011
 */
class RolesController extends CController {

	const PAGE_SIZE = 10;

	public function getSubmenu()
	{
		$all = array();
		if(Yii::app()->user->checkAccess('Roles.canCreate'))
		{
			$all['create'] = array(
					'icon' => Yii::app()->request->baseUrl . '/images/add.png',
					'label' => Yii::t('submenu', 'New role'),
					'href' => array('create')
				);
		}

		if(Yii::app()->user->checkAccess('Roles.canList'))
		{
			$all['admin'] = array(
					'icon' => Yii::app()->request->baseUrl . '/images/list.png',
					'label' => Yii::t('submenu', 'Manage roles'),
					'href' => array('admin')
				);
		}
		
		if ($this->_model != null) {
			if(Yii::app()->user->checkAccess('Roles.canUpdate'))
			{
				$all['update'] = array(
						'icon' => Yii::app()->request->baseUrl . '/images/edit.png',
						'label' => Yii::t('submenu', 'Update role'),
						'href' => array ('update','id' => $this->_model->name)
					);
			}
			if(Yii::app()->user->checkAccess('Roles.canDelete'))
			{
				$all['delete'] = array(
						'icon' => Yii::app()->request->baseUrl . '/images/del.png',
						'label' => Yii::t('submenu', 'Delete user'),
						'link' => array (
							'submit' => array ('delete','id' => $this->_model->name),
							'confirm' => Yii::t('submenu', 'Are you sure?')
						)
					);
			}
		}
		
		return $all;
	}

	/**
	 * @var string specifies the default action to be 'list'.
	 */
	public $defaultAction = 'admin';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters() {
		return array (// perform access control for CRUD operations
			'accessControl'
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array (
			array(
				'allow', 
				'actions' => array(
					'admin', 'show'
				),
				'roles' => array('Roles.canList')
			),
			array(
				'allow', 
				'actions' => array(
					'update'
				),
				'roles' => array('Roles.canUpdate')
			),
			array(
				'allow', 
				'actions' => array(
					'create'
				),
				'roles' => array('Roles.canCreate')
			),
			array(
				'allow', 
				'actions' => array(
					'delete'
				),
				'roles' => array('Roles.canDelete')
			),
			array (
				'deny', // deny all users
				'users' => array (
					'*'
				)
			)
		);
	}

	/**
	 * Shows a particular model.
	 */
	public function actionShow() {
		$this->render('show', array (
			'model' => $this->loadrole()
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionCreate() {
		$model = new RoleForm();

		if (!isset ($_POST['RoleForm'])) {
			$this->render('create', array (
				'model' => $model
			));
		} else {
			$arr = $_POST['RoleForm'];

			if ($arr == null) {
				$this->render('create', array (
					'model' => $model
				));
			} else {
				$model->scenario = RoleForm::CREATE;

				if (isset ($arr['name'])) {
					$model->attributes = $arr;
					$model->validate();
					if (!$model->hasErrors() && $model->save()) {
						$this->redirect(array (
							'show',
							'id' => $model->name
						));
					} else {
						$this->render('create', array (
							'model' => $model
						));
					}
				} else {
					$this->render('create', array (
						'model' => $model
					));
				}
			}
		}
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionUpdate() {
		$user = $this->loadrole();
		$model = new RoleForm();
		$model->load ($this->_model);

		$arr = null;

		if (isset ($_POST['RoleForm']))
			$arr = $_POST['RoleForm'];

		if ($arr == null) {
			$this->render('update', array (
				'model' => $model
			));
		} else {
			$model->scenario = RoleForm::UPDATE;
			$model->attributes = $arr;
			$model->validate();
			if (!$model->hasErrors() && $model->save()) {
				$this->redirect(array (
					'show',
					'id' => $model->name
				));
			} else {
				$this->render('update', array (
					'model' => $model
				));
			}
		}
	}


	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'list' page.
	 */
	public function actionDelete() {
		if (Yii::app()->request->isPostRequest) {
			// we only allow deletion via POST request
			$role = $this->loadrole($_POST['id']);
			Yii::app()->authManager->removeAuthItem($role->name);
			$this->redirect(array ('admin'));
		} else
			throw new CHttpException(400, Yii::t('user', 'Invalid request. Please do not repeat this request again.'));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin() {
		$this->processAdminCommand();

		$criteria = new CDbCriteria;

		$pages = new CPagination(count(Yii::app()->authManager->getRoles()));
		$pages->pageSize = self::PAGE_SIZE;
		$pages->applyLimit($criteria);

		//$sort = new CSort('user');
		//$sort->applyOrder($criteria);

		$models = Yii::app()->authManager->getRoles();

		$this->render('admin', array (
			'models' => $models,
			'pages' => $pages,
			//'sort' => $sort
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
	 */
	public function loadrole($id = null) {
		if ($this->_model === null) {
			if ($id !== null || isset ($_GET['id']))
			{
				$item = Yii::app()->authManager->getAuthItem($_GET['id']);
				if ($item->type == CAuthItem::TYPE_ROLE)
				{
					$this->_model = $item;
				}
			}
			if ($this->_model === null)
				throw new CHttpException(404, Yii::t('user', 'The requested page does not exist.<br />No role with id {id} found.', array (
					'{id}' => $_GET['id']
				)));
		}
		return $this->_model;
	}

	/**
	 * Executes any command triggered on the admin page.
	 */
	protected function processAdminCommand() {
		if (isset ($_POST['command'], $_POST['id']) && $_POST['command'] === 'delete') {
			$role = $this->loadrole($_POST['id']);
			Yii::app()->authManager->removeAuthItem($role->name);
			// reload the current page to avoid duplicated delete actions
			$this->refresh();
		}
	}
}
?>
